import React from 'react';
import { Button, Form, Row, Col } from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import { DownOutlined, UpOutlined } from '@ant-design/icons';

export interface QueryFilterFormProps {
  /** 表单提交函数 */
  onSubmit: Function;
  /** 表单重置回调函数 */
  onReset?: Function;
  colon: boolean;
  loading: boolean;
}

export interface QueryFilterFormState {
  /** 是否隐藏按钮 */
  hideBtn: boolean;
  /** 收缩的，默认为true，表示收起，但需要显示为展开 */
  collapsed: boolean;
}

const FormItem = Form.Item;
/** 保存栏位隐藏时，栏位的name属性，方便清除数据 */
let hideInputComps: string[] = [];

class QueryFilterForm extends React.PureComponent<QueryFilterFormProps, QueryFilterFormState> {

  formRef = React.createRef<FormInstance>();

  state: QueryFilterFormState = {
    hideBtn: false,
    collapsed: true,
  }

  /**
   * 表单提交
   */
  handleSubmit = () => {
    console.log('handleSubmit');
    // 收集表单数据
    // 传递回父组件
    // const fieldsValue = this.formRef.current!.getFieldsValue();
    // console.log('Received values of form: ', fieldsValue);
    // const { onSubmit } = this.props;
    // if (onSubmit) {
    //   onSubmit({
    //     ...fieldsValue
    //   });
    // }
    this.formRef.current!.validateFields().then(fieldsValue => {
      console.info(fieldsValue);
      const values = {
        ...fieldsValue
      };
      console.log('Received values of form: ', values);
      const { onSubmit } = this.props;
      if (onSubmit) {
        onSubmit({
          ...values
        });
      }
    }).catch();
  }

  handleReset = () => {
    this.formRef.current!.resetFields();
    const { onReset } = this.props;
    if (onReset) {
      onReset();
    }
  }

  /**
   * 按下键盘回车键触发函数
   * @param event 按下键盘事件封装类
   */
  handleEnterKey = (event: any) => {
    if (event.key === 'Enter') {
      console.log('anxiahuiche');
      this.handleSubmit();
    }
  }

  colformItemRender = (item: any, index: number) => {
    const { name, hidden } = item.props;
    // console.info(name, hidden);
    if (hidden) {
      // 栏位隐藏后，需要清除栏位的值
      hideInputComps.push(name);
      return null;
    }
    const itemKey = name || index;
    return (
      <Col span={6} key={itemKey}>
        {item}
      </Col>
    );
  }

  formItemRender = (collapsed: boolean, children: any, totalSize: number) => {
    // 收起时，最多展示3个栏位+查询按钮
    let newChildren: any[] = [];
    let maxCount = totalSize;
    if (collapsed) {
      maxCount = 3;
      // 收起时，清除栏位集合，重新计算
      hideInputComps = [];
    }
    // 展开时，根据顺序拼接
    React.Children.forEach(children, (child, index) => {
      if (index < maxCount) {
        newChildren.push(this.colformItemRender(child, index));
      } else {
        newChildren.push(this.colformItemRender(React.cloneElement(child, {
          hidden: true
        }), index));
      }
    });
    return newChildren;
  }

  setCollapsed = (collapsed: boolean) => {
    this.setState({
      collapsed: !collapsed
    });
    // 收起时，清除隐藏栏位的值
    console.info(collapsed, hideInputComps);
    if (!collapsed && hideInputComps.length > 0) {
      this.formRef.current!.resetFields([...hideInputComps]);
    }
  }

  render() {
    const { colon, loading, children } = this.props;
    // 收缩的，默认为true，表示收起，但需要显示为展开
    const { collapsed } = this.state;
    // 统计控件的数量
    let totalSize = React.Children.count(children);
    // 控件数量少于4个，则没有高级搜索标识
    const hideBtn = totalSize < 4 ? true : false;
    // 提交按钮列的偏移量，保证能够在行的最后一列
    let offset = 0;
    if (!hideBtn && collapsed) {
      offset = 24 - ((totalSize - 1 % 4) + 1) * 6;
    } else {
      offset = 24 - ((totalSize % 4) + 1) * 6;
    }
    const doms = this.formItemRender(collapsed, children, totalSize);

    return (
      <Form layout='horizontal'
        autoComplete='off'
        ref={this.formRef}
        onKeyUp={this.handleEnterKey}
        style={{marginBottom: '16px'}}
      >
        <Row gutter={{xs: 8, sm: 16, md: 24, lg: 32}}>
          {doms}
          <Col span={6} offset={offset} style={{
            textAlign: 'end'
          }}>
            <FormItem label=' ' colon={colon}>
              <Button type='primary' loading={loading} onClick={this.handleSubmit} >
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                  重置
                </Button>
                {!hideBtn && (
                  <a style={{ marginLeft: 8, fontSize: 16 }} onClick={() => this.setCollapsed(collapsed)}>
                    {!collapsed ? '收起': '展开'}{!collapsed ? <UpOutlined /> : <DownOutlined/>}
                  </a>
                )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

export default QueryFilterForm;